package org.kitten.core.util;

import static org.kitten.core.util.DateUtil.HOUR;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 定时器类.
 * 
 * @author sb.yin(uniquejava@gmail.com)
 * @version 1.0
 * @since 2010-5-17
 */
public class MyTimerTask {

	/**
	 * hms指在哪一时间点执行，数组中三个元素分别表示hourOfDay,minute,second.
	 */
	private int[] hms = new int[] { 0, 0, 0 };
	/**
	 * hms转换成的时间值.
	 */
	private Date firstTime;

	/**
	 * interval,时间间隔,毫秒数
	 */
	private int interval = 24 * HOUR;
	/**
	 * dayOffset,从哪天开始,0表示今天,1表示明天，依此类推.
	 */
	private int dayOffset = 0;
	/**
	 * 要执行的任务
	 */
	private TimerTask taskToRun;
	private Timer timer;

	/**
	 * 
	 * @param strTime
	 *            格式"HH:mm:ss"
	 * @param interval
	 *            毫秒数
	 * @param dayOffset
	 * @param taskToRun
	 */
	public MyTimerTask(String strTime, int interval, int dayOffset,
			TimerTask taskToRun) {
		String[] str = strTime.split(":");
		for (int i = 0; i < str.length; i++) {
			hms[i] = Integer.parseInt(str[i]);
		}
		Calendar c = new GregorianCalendar();
		c.add(Calendar.DATE, this.dayOffset);
		Calendar result = new GregorianCalendar(c.get(Calendar.YEAR), c
				.get(Calendar.MONTH), c.get(Calendar.DATE), hms[0], hms[1],
				hms[2]);
		this.firstTime = result.getTime();

		this.interval = interval;
		this.dayOffset = dayOffset;
		this.taskToRun = taskToRun;

	}

	public MyTimerTask(Date firstTime, int interval, TimerTask taskToRun) {
		this.firstTime = firstTime;
		this.interval = interval;
		this.dayOffset = 0;
		this.taskToRun = taskToRun;
	}

	public void run() {
		if (timer != null) {
			cancel();
		}
		timer = new Timer();
		// 这个方法有毛病，如果时间点是今天，启动时又过了时间点，会把先前的都补上来，冏
		// timer.scheduleAtFixedRate(taskToRun, firstTime, interval);
		timer.schedule(taskToRun, firstTime, interval);
	}

	public void cancel() {
		this.timer.cancel();
	}
}
